package com.example.data.factory.service.service.Impl;

import com.example.data.factory.common.util.ParamParser;
import com.example.data.factory.entity.entity.Interface;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class InterfaceTestService {
    private static final Logger logger = LoggerFactory.getLogger ( InterfaceTestService.class );
    private final ObjectMapper objectMapper = new ObjectMapper ();

    /**
     * 测试接口
     */
    public String testInterface(Interface iface, Map<String, String> queryParams, Map<String, Object> bodyParams) throws IOException {
        // 构造完整的 URL
        String url = iface.getProtocol () + "://" + iface.getIpAndProt () + iface.getPath ();
        logger.info ( "构造的 URL: {}", url );

        // 如果是 GET 请求，拼接查询参数
        if ("get".equalsIgnoreCase ( iface.getRequest () )) {
            HttpUrl.Builder httpUrlBuilder = HttpUrl.parse ( url ).newBuilder ();
            if (queryParams != null) {
                for (Map.Entry<String, String> entry : queryParams.entrySet ()) {
                    httpUrlBuilder.addQueryParameter ( entry.getKey (), entry.getValue () );
                }
            }
            url = httpUrlBuilder.build ().toString ();
            logger.info ( "GET 请求的完整 URL: {}", url );
        }

        // 如果是 POST 请求，打印请求体
        if ("post".equalsIgnoreCase ( iface.getRequest () )) {
            if (bodyParams != null) {
                try {
                    String requestBody = objectMapper.writeValueAsString ( bodyParams );
                    logger.info ( "POST 请求体: {}", requestBody );
                } catch (Exception e) {
                    logger.error ( "请求体 JSON 转换失败", e );
                }
            }
        }

        // 模拟返回结果
        Map<String, Object> mockResponse = new HashMap<> ();
        mockResponse.put ( "status", "success" );
        mockResponse.put ( "message", "模拟接口调用成功" );

        // 处理返回的参数逻辑
        if (queryParams == null || queryParams.isEmpty ()) {
            // 如果没有传入参数，使用动态生成的默认参数
            Map<String, String> defaultParams = ParamParser.parseInputParams ( String.valueOf ( iface.getInputParam () ) );
            logger.info ( "默认参数: {}", defaultParams );
            mockResponse.put ( "data", defaultParams );
        } else {
            // 如果传入了参数，解码并返回传入的参数
            Map<String, String> decodedParams = new HashMap<> ();
            for (Map.Entry<String, String> entry : queryParams.entrySet ()) {
                String decodedValue = URLDecoder.decode ( entry.getValue (), StandardCharsets.UTF_8 );
                decodedParams.put ( entry.getKey (), decodedValue );
            }
            mockResponse.put ( "data", decodedParams );
        }

        // 返回 JSON 格式的字符串
        try {
            return objectMapper.writeValueAsString ( mockResponse );
        } catch (Exception e) {
            logger.error ( "JSON 转换失败", e );
            throw new RuntimeException ( "JSON 转换失败", e );
        }
    }
}


